#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
# Copyright 2011 zod.yslin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 
# Author: zod.yslin
# Email: 
# File Name: generators.py
# Description: 
#   Generators are a simple and powerful tool for creating iterators.
# Edit History: 
#   2011-08-09    File created.
#===============================================================================

"""
What makes generators so compact is that the __iter__() and next() methods are created automatically.
"""
def reverse(data):
    for index in range(len(data)-1, -1, -1):
        print index
        """
        Each time next() is called, the generator resumes where it left-off 
        (it remembers all the data values and which statement was last executed).
        """
        yield data[index] 

for char in reverse('golf'):
    print char

# help(range)

#==============================================================================
# Generator Expressions
# Some simple generators can be coded succinctly as expressions using a syntax 
# similar to list comprehensions but with parentheses instead of brackets. 
# These expressions are designed for situations where the generator is used 
# right away by an enclosing function. Generator expressions are more compact 
# but less versatile than full generator definitions and tend to be more memory 
# friendly than equivalent list comprehensions.
#==============================================================================

print sum(i*i for i in range(10))                 # sum of squares

xvec = [10, 20, 30]
yvec = [7, 5, 3]

print sum(x*y for x,y in zip(xvec, yvec))         # dot product

from math import pi, sin
sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91))
#unique_words = set(word  for line in page  for word in line.split())
#valedictorian = max((student.gpa, student.name) for student in graduates)
data = 'golf'
list(data[i] for i in range(len(data)-1,-1,-1))
